from flask import Blueprint,jsonify,request

from utils.db import db1

from comm import get_data

bp_zuzhi = Blueprint('zuzhi',__name__)




def xtree(data):
    if len(data) <= 0:
        return data
    lst=[]
    tree={}
    for i in data:
        i["label"] = i["name"]
        tree[i["id"]]=i
    for j in data:
        pid = j["pid"]
        if pid == 0:
            lst.append(j)
        else:
            if "children" not in tree[pid]:
                tree[pid]["children"] = []
            tree[pid]["children"].append(j)
    print(lst)
    return lst







@bp_zuzhi.route('/zuzhi')
def zuzhi():
    sql = "select * from dept"

    res = db1.find_all(sql)

    res = xtree(res)

    return jsonify({'code':200,'list':res})




@bp_zuzhi.route('/addzuzhi',methods=["POST"])
def addzuzhi():
    data = get_data()

    sql = "insert into dept values(0,'%s','%s',%d)" % (data['name'],data['code'],int(data['pid']))

    db1.update(sql)

    return jsonify({'code':200,'mes':'添加成功'})





def get_resourcelist(self, uid, type):
    sql = "select r.name,r.url,r.id,pr.id as pid,pr.name as pname from user_resource as ur left join resource as r on ur.resourceid=r.id left join resource as pr on pr.id=r.pid where ur.userid=%d and r.type=%d union select r.name,r.url,r.id,pr.id as pid,pr.name as pname from user_role as ur left join role_resource as rr on ur.roleid=rr.roleid left join resource as r on rr.resource=r.id left join resource as pr on pr.id=r.pid where ur.userid=%d and r.type=%d" % (
    int(uid), int(type), int(uid), int(type))
    res = db1.find_all(sql)
    return res


